import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

import { login } from '@/api/users'

export default new Vuex.Store({
  plugins: [
    createPersistedState({
      storage: localStorage
    })
  ],
  state: {
    userInfo: {},
    token: ''
  },
  mutations: {
    SET_USERINFO(state, payload) {
      state.userInfo = payload
    },
    SET_TOKEN(state, payload) {
      state.token = payload
    }
  },
  actions: {
    loginAsync(store, payload) {
      return login(payload).then(({ userInfo, token }) => {
        store.commit('SET_USERINFO', userInfo)
        store.commit('SET_TOKEN', token)
        return {
          success: true
        }
      })
    },
    logoutAsync(store) {
      store.commit('SET_USERINFO', {})
      store.commit('SET_TOKEN', '')
    }
  },
  modules: {}
})
